/*global pi, ArrayBuffer, Uint8Array*/

pi.mod.define('pi.jsbuffer', function (pi) {
	"use strict";
	var indexBufferGetCrc32, module = {},
		log = pi.log,
		dllPath = "TestDll.dll";
	/*
	 * 计算buffer的crc32
	 * buf: js buffer or c pointer
	 */
	indexBufferGetCrc32 = 0;
	module.getCrc32 = function (buf, len) {
		if (!indexBufferGetCrc32) {
			indexBufferGetCrc32 = pi.vcall.register(dllPath, "BufferGetCrc32", pi.vcall.TYPE_INT, [pi.vcall.TYPE_POINTER, pi.vcall.TYPE_INT]);
		}
		return pi.vcall.invoke(indexBufferGetCrc32, buf, len);
	};

	/*
		output buffer(ArrayBuffer, Uint8Array...) like this:
		00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
		----------------------------------------------------
		0000 6f 00 00 00 1f 00 03 00 00 00 00 00 00 00 00 00
		0010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
	 */
	module.printBuffer = function (buf, start, len, countPerLine) {
		var i, v, sb, sbSep, strV;
		//ArrayBuffer 不能使用[]访问buffer数据,[]访问的是一般数组数据
		if (buf instanceof ArrayBuffer) {
			buf = new Uint8Array(buf);
		}
		//set default arguments
		if (!start) {
			start = 0;
		}
		if (!len || len > buf.byteLength) {
			len = buf.byteLength;
		}
		if (!countPerLine) {
			countPerLine = 16;
		}
		log("start=" + start + ", len=" + len + ", countPerLine=" + countPerLine + ", buffer contents:");

		sb = new pi.string.StringBuffer();
		sbSep = new pi.string.StringBuffer();
		//output header
		sb.append("     ");
		sbSep.append("-----");
		for (i = 0; i < countPerLine; i += 1) {
			sb.append(pi.string.padLeft(i.toString(16), 2) + " ");
			sbSep.append("---");
		}
		log(sb.toString());
		log(sbSep.toString());

		//now, the contents:
		sb = new pi.string.StringBuffer();
		for (i = 0; i < len; i += 1) {
			if (i % countPerLine === 0) {
				if (i) {
					sb.append("\n");
				}
				sb.append(pi.string.padLeft(i.toString(16), 4) + " ");
			}
			v = buf[start + i];
			strV = pi.string.padLeft(v.toString(16), 2);
			sb.append(strV + " ");
		}
		log(sb.toString());
	};

	//file with 0xcc
	module.fillBuffer = function (buf, val) {
		var i, u8, len;
		if (typeof (val) === "undefined") {
			val = 0xcc;
		}
		len = buf.byteLength;
		u8 = new Uint8Array(len); //use Uin8Array,避免频繁调用vcall_write_buffer
		for (i = 0; i < len; i += 1) {
			u8[i] = val;
		}
		pi.vcall.writeBuffer(u8, buf, pi.vcall.TYPE_BUFFER, 0, 0, len);
	};

	//create with filling 0xcc
	module.createBuffer = function (len) {
		var buf = new ArrayBuffer(len);
		pi.jsbuffer.fillBuffer(buf);
		return buf;
	};

	//通过ArrayBuffer创建Uint8Array,这样可以传递指定偏移量的ArrayBuffer
	//offset: 相对于ArrayBuffer
	//[len, arrayBuffer.byteLength - offset], u8的长度
	module.u8 = function (arrayBuffer, offset, len) {
		var u8;
		len = pi.util.DV(len, arrayBuffer.byteLength - offset);
		u8 = new Uint8Array(arrayBuffer, offset, len);
		return u8;
	};

	return module;
});